<?php
/**
 * Created by PhpStorm.
 * User: Guojunchen
 * Date: 2018/4/12
 * Time: 11:23
 */

namespace app\app\controller;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use think\Controller;
use app\common\lib\User;
/**
 * API模块 公共控制器
 * Class Common
 * @package app\api\controller
 */
class Common extends Controller{

    public $headers = '';
    public $uid = 0;

    public function _initialize(){
        $this->checkRequestAuth();
        $this->getUid();
    }

    /**
     * 每次app请求，通过加密校验请求数据是否合法
     */
    public function checkRequestAuth(){
        // 通过header传递加密sign和客户端设备基本信息
        //（操作系统device-os，客户端版本号app-ver，系统版本os-ver，设备版本号device-ver）
        $headers = request()->header();
        // 参数校验
        if (empty($headers['sign'])){
            throw new ApiException('sign不存在', 400);
        }
        if (!in_array($headers['device-os'], config('app.device_os'))){
            throw new ApiException('操作系统不合法', 400);
        }
        // sign解密校验
        if (!IAuth::checkSignPass($headers)){
            throw new ApiException('授权码sign失败', 401);
        }

        $this->headers = $headers;
    }

    public function getUid(){
        $headers = request()->header();
        $access_token = empty($headers['access-token']) ? '' : $headers['access-token'];
        $access_token = stripslashes($access_token);
        $access_token = str_replace(' ', '+', $access_token);
        $logined_info = User::decode_token($access_token, 'access_token');
        if (isset($logined_info['uid'])){
            (int) $this->uid = $logined_info['uid'];
        }
    }
}